import { createToast, injectToastStyles } from '../common/toast.js';
import { initializeSwitchPage } from './components/switch.js';
import { initializeToolsPage } from './components/tools.js';

// 页面配置
const PAGES = {
    switch: {
        init: initializeSwitchPage,
        title: '切换集群/命名空间'
    },
    tools: {
        init: initializeToolsPage,
        title: '快捷工具'
    }
};

class PopupManager {
    constructor() {
        this.currentPage = null;
        this.contentEl = document.querySelector('.content');
        this.menuItems = document.querySelectorAll('.menu-item');
    }

    async init() {
        injectToastStyles();
        this.bindEvents();
        await this.loadPage('switch'); // 加载默认页面
    }

    bindEvents() {
        this.menuItems.forEach(item => {
            item.addEventListener('click', () => {
                const pageName = item.getAttribute('data-page');
                this.switchPage(pageName);
            });
        });
    }

    async loadPage(pageName) {
        try {
            const response = await fetch(`components/${pageName}.html`);
            const html = await response.text();
            this.contentEl.innerHTML = html;
            
            // 初始化页面
            const page = PAGES[pageName];
            if (page?.init) {
                await page.init();
            }
            
            this.currentPage = pageName;
            return true;
        } catch (error) {
            console.error(`加载页面失败: ${pageName}`, error);
            createToast(`加载${PAGES[pageName]?.title || pageName}失败`, 'error');
            return false;
        }
    }

    async switchPage(pageName) {
        if (this.currentPage === pageName) return;
        
        // 更新菜单状态
        this.menuItems.forEach(item => {
            item.classList.toggle('active', item.getAttribute('data-page') === pageName);
        });

        // 加载新页面
        await this.loadPage(pageName);
    }
}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    const popup = new PopupManager();
    popup.init();
});